package cn.xhy.module.purchase.service.documentserial;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import cn.xhy.module.purchase.controller.admin.documentserial.vo.*;
import cn.xhy.module.purchase.dal.dataobject.documentserial.DocumentSerialDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.xhy.module.purchase.dal.mysql.documentserial.DocumentSerialMapper;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

import static cn.hutool.core.date.DatePattern.NORM_DATETIME_MS_FORMATTER;
import static cn.hutool.core.date.DatePattern.NORM_DATE_FORMAT;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.xhy.module.purchase.enums.ErrorCodeConstants.DOCUMENT_SERIALN_NOT_EXISTS;
import static cn.xhy.module.purchase.enums.ErrorCodeConstants.DOCUMENT_SERIAL_NOT_EXISTS;

/**
 * 单据序号 Service 实现类
 *
 * @author xhy
 */
@Service
@Validated
public class DocumentSerialServiceImpl implements DocumentSerialService {

    @Resource
    private DocumentSerialMapper documentSerialMapper;

    @Override
    public String createDocumentSerial(DocumentSerialSaveReqVO createReqVO) {
        if (StringUtils.isEmpty(createReqVO.getInitial())) {
            throw new IllegalArgumentException("初始值不能为空");
        }
        DocumentSerialDO createObjDocumentSerialDO = BeanUtils.toBean(createReqVO, DocumentSerialDO.class);
        LocalDate now = LocalDate.now();
        String dateTime = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String documentSerial;
        Optional<DocumentSerialDO> optionalDocumentSerialDO = Optional.ofNullable(documentSerialMapper.selectOne(
                new LambdaQueryWrapperX<DocumentSerialDO>()
                        .eq(DocumentSerialDO::getInitial, createReqVO.getInitial())
                        .eq(DocumentSerialDO::getDjDate, now)
        ));
        if (optionalDocumentSerialDO.isPresent() && optionalDocumentSerialDO.get().getSerialNumber() != null) {
            int i = optionalDocumentSerialDO.get().getSerialNumber() + 1;
            documentSerialMapper.update(new DocumentSerialDO().setSerialNumber(i),
                    new LambdaQueryWrapperX<DocumentSerialDO>()
                            .eq(DocumentSerialDO::getInitial, createReqVO.getInitial())
                            .eq(DocumentSerialDO::getDjDate, now)
            );
            String format = null;
            if (optionalDocumentSerialDO.get().getSerialNumber().toString().length() == 1) {
                format = "00" + optionalDocumentSerialDO.get().getSerialNumber();
            } else if (optionalDocumentSerialDO.get().getSerialNumber().toString().length() == 2) {
                format = "0" + optionalDocumentSerialDO.get().getSerialNumber();
            }
            documentSerial = createReqVO.getInitial() + dateTime + format;
            return documentSerial;
        }
        createObjDocumentSerialDO.setDjDate(now);
        createObjDocumentSerialDO.setSerialNumber(1);
        createObjDocumentSerialDO.setCreateTime(LocalDateTimeUtil.now());
        documentSerialMapper.insert(createObjDocumentSerialDO);
        documentSerial = createReqVO.getInitial() + dateTime + "001";
        return documentSerial;
    }

    @Override
    public void updateDocumentSerial(DocumentSerialSaveReqVO updateReqVO) {
        // 校验存在
        validateDocumentSerialExists(updateReqVO.getId());
        // 更新
        DocumentSerialDO updateObj = BeanUtils.toBean(updateReqVO, DocumentSerialDO.class);
        documentSerialMapper.updateById(updateObj);
    }

    @Override
    public void deleteDocumentSerial(Long id) {
        // 校验存在
        validateDocumentSerialExists(id);
        // 删除
        documentSerialMapper.deleteById(id);
    }

    private void validateDocumentSerialExists(Long id) {
        if (documentSerialMapper.selectById(id) == null) {
            throw exception(DOCUMENT_SERIAL_NOT_EXISTS);
        }
    }

    @Override
    public DocumentSerialDO getDocumentSerial(Long id) {
        return documentSerialMapper.selectById(id);
    }

    @Override
    public PageResult<DocumentSerialDO> getDocumentSerialPage(DocumentSerialPageReqVO pageReqVO) {
        return documentSerialMapper.selectPage(pageReqVO);
    }

}
